#include <gr_graph_fun.h>
#include "interface.h"

GtkWidget*
create_fileselectionXGMML(GraphFrame **graph)
{
  GtkWidget *fileselectionXGMML;
  GtkWidget *ok_button1;
  GtkWidget *cancel_button1;

  fileselectionXGMML = gtk_file_selection_new ("Save As ...");
  gtk_widget_set_name (fileselectionXGMML, "fileselectionXGMML");
  gtk_container_set_border_width (GTK_CONTAINER (fileselectionXGMML), 10);
  gtk_window_set_destroy_with_parent (GTK_WINDOW (fileselectionXGMML), TRUE);

  ok_button1 = GTK_FILE_SELECTION (fileselectionXGMML)->ok_button;
  gtk_widget_set_name (ok_button1, "ok_button1");
  gtk_widget_show (ok_button1);
  GTK_WIDGET_SET_FLAGS (ok_button1, GTK_CAN_DEFAULT);

  cancel_button1 = GTK_FILE_SELECTION (fileselectionXGMML)->cancel_button;
  gtk_widget_set_name (cancel_button1, "cancel_button1");
  gtk_widget_show (cancel_button1);
  GTK_WIDGET_SET_FLAGS (cancel_button1, GTK_CAN_DEFAULT);

  gtk_signal_connect (GTK_OBJECT (fileselectionXGMML), "response",
                      GTK_SIGNAL_FUNC (saveXGMMLtoFile),
                      (void *)graph);
  
  gtk_signal_connect  (GTK_OBJECT(cancel_button1), "clicked",
		  GTK_SIGNAL_FUNC (gtk_widget_destroy),
		  GTK_OBJECT(fileselectionXGMML));

  /* Store pointers to all widgets, for use by lookup_widget(). */
  GLADE_HOOKUP_OBJECT_NO_REF (fileselectionXGMML, fileselectionXGMML, "fileselectionXGMML");
  GLADE_HOOKUP_OBJECT_NO_REF (fileselectionXGMML, graph, "graphptr");
  GLADE_HOOKUP_OBJECT_NO_REF (fileselectionXGMML, ok_button1, "ok_button1");
  GLADE_HOOKUP_OBJECT_NO_REF (fileselectionXGMML, cancel_button1, "cancel_button1");

  return fileselectionXGMML;
}

void
saveXGMMLtoFile                        (GtkDialog       *dialog,
                                        gint             arg1,
                                        gpointer         user_data)
{
	GtkFileSelection *filesel = (GtkFileSelection *)dialog;
	const char *file = gtk_file_selection_get_filename(filesel);
	GraphFrame **graphptr = (GraphFrame **)user_data;
	
	FILE *output;
	long len;
	char *XGMML;
	
	if(!(output = fopen(file,"w+"))) {
		fprintf(stderr,"FILE NOT SAVED!\n");
		return;
	}
	gtk_widget_destroy((GtkWidget *)dialog);
	
	if(!graphptr || !*graphptr) {
		fprintf(stderr,"NO GRAPH TO SAVE!\n");
		return;
	}
	
	XGMML = get_text_graph(*graphptr,&len);
	
	if(fwrite(XGMML,sizeof(char),(size_t)len,output) != len) {
		fprintf(stderr,"ERROR WRITING GRAPH!\n");
	}
	
}
